import { IDBStoreCreate } from './storeCreate'
import { IDBStoreDelete } from './storeDelete'
import { IDBStoreRead } from './storeRead'
import { IDBStoreUpdate } from './storeUpdate'
import { IDBSchemaStore, IDBDataType, IDBStoreBulkDeleteOptions, IDBStoreBulkReadOptions } from './types'

export class IDBStore {
  private db: IDBDatabase | null = null
  private readAPI: IDBStoreRead
  private deleteAPI: IDBStoreDelete
  private createAPI: IDBStoreCreate
  private updateAPI: IDBStoreUpdate
  storeName: string
  schema: IDBSchemaStore

  constructor(storeName: string, schema: IDBSchemaStore, db: IDBDatabase) {
    this.storeName = storeName
    this.schema = schema
    this.db = db
    this.readAPI = new IDBStoreRead(this)
    this.deleteAPI = new IDBStoreDelete(this)
    this.createAPI = new IDBStoreCreate(this)
    this.updateAPI = new IDBStoreUpdate(this)
  }

  getDB(): IDBDatabase {
    if (!this.db) {
      throw new Error('DB not ready')
    }
    return this.db
  }

  getStoreName(): string {
    return this.storeName
  }

  getSchema(): IDBSchemaStore {
    return this.schema
  }

  /** ==================== read API start ================================ */
  count() {
    return this.readAPI.count()
  }

  read(id: string | number) {
    return this.readAPI.read(id)
  }

  readByIds(ids: string[] | number[]) {
    return this.readAPI.readByIds(ids)
  }

  bulkRead(options: IDBStoreBulkReadOptions) {
    return this.readAPI.bulkRead(options)
  }

  readAllByPage(offset?: number, limit?: number) {
    return this.readAPI.readAllByPage(offset, limit)
  }

  readAll() {
    return this.readAPI.readAll()
  }
  /** ==================== read API end ================================ */

  /** ------------------- create API start ----------------------------- */
  create(record: IDBDataType) {
    return this.createAPI.create(record)
  }
  bulkCreate(records: IDBDataType[]) {
    return this.createAPI.bulkCreate(records)
  }
  /** ------------------- create API end ----------------------------- */

  /** ==================== update API start ================================ */
  update(record: IDBDataType) {
    return this.updateAPI.update(record)
  }
  merge(record: IDBDataType) {
    return this.updateAPI.merge(record)
  }
  /** ==================== update API end ================================ */

  /** -------------------- delete API start --------------------------------- */
  bulkDelete(options: IDBStoreBulkDeleteOptions) {
    return this.deleteAPI.bulkDelete(options)
  }

  delete(id: string | number) {
    return this.deleteAPI.delete(id)
  }

  clear() {
    return this.deleteAPI.clear()
  }
  /** -------------------- delete API end --------------------------------- */

  destroy() {
    this.db = null
    this.storeName = ''
    this.schema = {} as IDBSchemaStore
  }
}
